package com.harisucici.websocketlib.room;


import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.paging.DataSource;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.Query;
import androidx.room.Transaction;
import androidx.room.Update;

import com.harisucici.websocketlib.entities.receive.SessionListReceive;

import java.util.ArrayList;
import java.util.List;

@Dao
public abstract class SessionListDao {

    MutableLiveData<List<SessionListReceive>> listLiveData;

    public MutableLiveData<List<SessionListReceive>> getListLiveData() {
        if (listLiveData == null) {
            listLiveData = new MutableLiveData<>();
        }
        return listLiveData;
    }

    @Insert
    public abstract void insertSession(SessionListReceive entity);

    @Insert
    public abstract void insertSessions(List<SessionListReceive> entities);

    @Delete
    public abstract void deleteSession(SessionListReceive entity);

    @Update
    public abstract void updateSession(SessionListReceive entity);

    @Update
    public abstract void updateSessions(List<SessionListReceive> entities);

    @Query("select * from SessionListReceive where top=:top order by timestamp desc")
    public abstract List<SessionListReceive> listSessionByTop(boolean top);

    @Query("select * from SessionListReceive order by timestamp desc")
    public abstract LiveData<List<SessionListReceive>> listSession();

    @Query("select * from SessionListReceive order by timestamp desc")
    public abstract DataSource.Factory<Integer, SessionListReceive> listSessionPaging();

    @Query("select * from SessionListReceive where timelineId=:timelineId")
    public abstract SessionListReceive findSessionById(String timelineId);

    @Query("select timelineId from SessionListReceive")
    public abstract List<String> findTimelineId();

    @Query("delete from SessionListReceive")
    public abstract void deleteAll();


    @Transaction
    public void listTopSession() {
        List<SessionListReceive> top = listSessionByTop(true);
        List<SessionListReceive> bottom = listSessionByTop(false);
        List<SessionListReceive> all = new ArrayList<>(5);
        all.addAll(top);
        all.addAll(bottom);
        listLiveData.postValue(all);
    }
}
